#include <iostream>
#include <vector>

using namespace std;

class ListNode {
public:
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}

public:
    int val;
    ListNode *next;
};

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr) {
            return nullptr;
        }
        // 创建哑结点
        ListNode *dummyNode = new ListNode(0);
        dummyNode->next = head;
        // 建立初始状态
        ListNode *pre = dummyNode;
        ListNode *node1 = head;
        ListNode *node2 = head->next;

        while (node1 != nullptr && node1->next != nullptr) {
            // 先处理前驱节点状态(pre和node1)
            pre->next = node2;
            node1->next = node2->next;
            // 处理当前节点
            node2->next = node1;
            // 状态后移
            pre = node1;
            node1 = node1->next;
            if (node1 != nullptr) {
                node2 = node1->next;
            }
        }
        ListNode *newHead = dummyNode->next;
        delete dummyNode;
        return newHead;
    }
    // 尾插法插入链表元素
    void insertNodeAtTail(ListNode *&head, int val) {
        ListNode *newNode = new ListNode(val);
        ListNode *currentNode = head;
        if (head == nullptr) {
            head = newNode;
            return;
        }
        while (currentNode->next != nullptr) {
            currentNode = currentNode->next;
        }
        currentNode->next = newNode;
        return;
    }
    // 打印链表元素
    void printfListNode(ListNode *head) {
        while (head != nullptr) {
            std::cout << head->val << "->";
            head = head->next;
        }
        std::cout << "NULL" << endl;
        return;
    }
};
int main()
{
    Solution *test = new Solution();
    vector<int> vec = {1, 2, 3, 4, 5, 6, 7 };
    ListNode *head = nullptr;
    // 插入节点
    for (const auto &v : vec) {
        test->insertNodeAtTail(head, v);
    }
    test->printfListNode(head); // 1->2->3->4->5->6->7->NULL
    ListNode *swapedHead = test->swapPairs(head);
    test->printfListNode(swapedHead); // 2->1->4->3->6->5->7->NULL

    delete test;
    system("pause");
    return 0;
}